$(function () {


    $("#waybills-tab").addClass("active");

    //============================================================================================
    //加载数据
    var allWaybillsQueryParams ={"pageSize":20,"currentPage":1,"params":{isRecycle:0}};
    var loadWaybills = function (queryParams) {
        if (queryParams == undefined) {
            //senderPhoneNo 可选,waybillStatus 必须,isRecycle 必须
            queryParams = {"currentPage":1,params: {isRecycle: 0}};
        }




        $.ajax({
            url: jspContext+'/workbench/1/waybills',
            type: 'post',
            contentType: 'application/json;charset=UTF-8',
            dataType: 'json',
            data: JSON.stringify(queryParams),
            success: function (result, textStatus, jqXHR) {
                if (result.status == 0) {
                    $('#idAllWaybillTotalCnt').html(result.totalSize);
                    showWaybillTable(result.data,"pendingWaybills");
                    showPagination(result.pageSize,result.currentPage,result.totalSize,$('#idAllwaybillsPagination'),function(pageIndex){
                        allWaybillsQueryParams["currentPage"] = pageIndex;
                        loadWaybills(allWaybillsQueryParams);
                    });
                }
            }
        });
    }



    var showWaybillTable = function (waybills) {

        var html = "";
        if (waybills.length == 0) {
            html = "<tr><td colspan='8' align='center'>没有数据....</td></tr>";
            $('#table-waybills tbody').html(html);
            return;
        }

        $.each(waybills, function (index, waybill) {
                html += "<tr>"
                    + "    <td>"
                    + "        <div class='checkbox'>"
                    + "            <label>"
                    + "                <input type='checkbox' data-my-waybill-id='" + waybill.waybillId + "'>"
                    + "            </label>"
                    + "        </div>"
                    + "    </td>"
                    + "    <td>" + waybill.sendDate + "</td>"
                    + "    <td>" + waybill.waybillNo + "</td>"
                    + "    <td>" + waybill.receiverName + "</td>"
                    + "    <td>" + waybill.startAddr + "</td>"
                    + "    <td>" + waybill.endAddr + "</td>"
                    + "    <td>" + getWaybillStatusText(waybill.waybillStatus) + "</td>"
                    + "    <td>"
                    + "        <button class='btn btn-primary my-waybill-details' data-my-waybill-id='" + waybill.waybillId + "'>点击查看详情</button>"
                    + "    </td>"
                    + "</tr>";
            }
        )
        ;


        $('#table-waybills tbody').html(html);
        $('#table-waybills .my-waybill-details').click(function () {
            var waybillId = $(this).data("my-waybill-id");
            window.location = jspContext+"/workbench/1/waybill/details?requestSrc=normal&waybillId=" + waybillId;
        });

    }




    //----------------------------------------------------

    //加入回收站
    $('#btnBatchRecycle').click(function () {

        var waybillIds = new Array();
        $('#table-waybills input[type="checkbox"]:checked').each(function (index, item) {

            var waybillId = $(this).data('my-waybill-id');
            console.log(waybillId);
            waybillIds.push(waybillId);

        });

        var params = {"params": waybillIds};
        $.ajax({
            url: jspContext+'/workbench/waybill/recycle',
            type: 'post',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(params),
            success: function (data) {
                console.log(data);
                refressAll();
            },
            error: function (XMLHttpRequest, textStatus) {
                console.log("错误：" + textStatus);
                this;
            }
        });


    });

    //-----------------------------
    //查询的按钮
    $('#idQueryButton').click(function () {
        var queryStr = $.trim($("#idQueryInput").val());

        if ($.trim(queryStr) != "") {
            allWaybillsQueryParams["queryStr"] = queryStr;
        }else{
            delete  allWaybillsQueryParams["queryStr"];
        }
        allWaybillsQueryParams["currentPage"] = 1;
        loadWaybills(allWaybillsQueryParams);
    });


    //分页
    showPagination = function(pageSize,currentPage,totalSize,target,action){
        //1 最多显示5项
        //2 向左向左显示上一页一下页
        //3.当页号是最后一项时点显示以当前页为中间项的
        var totalPages = Math.ceil(totalSize/pageSize);
        var maxItems = 5;
        var startIndex = 1;
        var endIndex = 1;
        if(totalPages <= maxItems){
            startIndex = 1;
            endIndex = totalPages;
        }else{
            if(currentPage <maxItems-1){
                startIndex =1
                endIndex = maxItems
            }else{
                startIndex = currentPage - Math.ceil(maxItems/2);
                endIndex = currentPage + maxItems-Math.ceil(maxItems/2)-1;
            }
        }

        var html = '';
        //回到第一页按钮
        if(currentPage<=1){
            html+='<li class="disabled "><a href="javascript:void(0)">&laquo;</a></li>';
        }else{
            html+='<li><a class="pagination-first-page" href="javascript:void(0)">&laquo;</a></li>';
        }
        //上一页按钮
        if(currentPage<=1){
            html+='<li class="disabled "><a href="javascript:void(0)">&lsaquo;</a></li>';
        }else{
            html+='<li><a class="pagination-previous-page" href="javascript:void(0)">&lsaquo;</a></li>';
        }
        for(var i=startIndex;i<=endIndex;i++){
            if(i==currentPage){
                html +='<li class="active"><a data-my-page-index="'+i+'" href="javascript:void(0)">'+i+'</a></li>';
            }else{
                html +='<li><a  class="pagination-index" data-my-page-index="'+i+'" href="javascript:void(0)">'+i+'</a></li>';
            }

        }


        //下一页
        if(currentPage==totalPages){
            html += '<li class="disabled" ><a href="javascript:void(0)">&rsaquo;</a></li>'
                  + '<li class="disabled"><a  href="javascript:void(0)">&raquo;</a></li>';
        }else{
            html += '<li><a class="pagination-next-page" href="javascript:void(0)">&rsaquo;</a></li>'
                + '<li><a  class="pagination-last-page" href="javascript:void(0)">&raquo;</a></li>';
        }


        $(target).html(html);
        $(target).find('a[class="pagination-index"]').click(function(e){
            //$(target).find('li').removeClass('active');
            //$(this).parent('li').addClass('active');
            var pageIndex =  $(this).data("my-page-index");
            action(pageIndex);
        });


        $(target).find('a[class="pagination-first-page"]').click(function(e){
            //第一页
            action(1);
        });
        $(target).find('a[class="pagination-previous-page"]').click(function(e){
            //上一页
            action(currentPage-1);
        });
        $(target).find('a[class="pagination-last-page"]').click(function(e){
            action(totalPages)
            //最后一页
        });
        $(target).find('a[class="pagination-next-page"]').click(function(e){
            //下一页
            action(currentPage+1);
        });

    };







    //待处理订单
    //============================================================================================
    var pendingWaybillsQueryParams={"pageSize":20,"currentPage":1,"params": {waybillStatus: 3, isRecycle: 0}};
    var loadPendingWaybills = function (queryParams) {
        if (queryParams == undefined) {
            //senderPhoneNo 可选,waybillStatus 必须,isRecycle 必须
            queryParams = {"pageSize":20,"currentPage":1,"params": {waybillStatus: 3, isRecycle: 0}};
        }
        $.ajax({
            url: jspContext+'/workbench/1/waybills',
            type: 'post',
            contentType: 'application/json;charset=UTF-8',
            dataType: 'json',
            data: JSON.stringify(queryParams),
            success: function (result, textStatus, jqXHR) {
                if (result.status == 0) {
                    $('#idPendingWaybillTotalCnt').html(result.totalSize);
                    showPendingWaybillTable(result.data);
                    showPagination(result.pageSize,result.currentPage,result.totalSize,$('#idPendingWaybillsPagination'),function(pageIndex){
                        pendingWaybillsQueryParams["currentPage"] = pageIndex;
                        loadPendingWaybills(pendingWaybillsQueryParams);
                    });
                }
            }
        });
    }

    function showPendingWaybillTable(waybills) {

        var html = "";
        if (waybills.length == 0) {
            html = "<tr><td colspan='8' align='center'>没有数据....</td></tr>";
            $('#table-waybills tbody').html(html);
            return;
        }

        $.each(waybills, function (index, waybill) {
                html += "<tr>"
                    + "    <td>"
                    + "        <div class='checkbox'>"
                    + "            <label>"
                    + "                <input type='checkbox'>"
                    + "            </label>"
                    + "        </div>"
                    + "    </td>"
                    + "    <td>" + waybill.sendDate + "</td>"
                    + "    <td>" + waybill.waybillNo + "</td>"
                    + "    <td>" + waybill.receiverName + "</td>"
                    + "    <td>" + waybill.startAddr + "</td>"
                    + "    <td>" + waybill.endAddr + "</td>"
                    + "    <td>" + getWaybillStatusText(waybill.waybillStatus) + "</td>"
                    + "    <td>"
                    + "        <div class='btn-group'>"
                    + "            <button type='button' class='btn btn-warning dropdown-toggle' data-toggle='dropdown'>"
                    + "                处理"
                    + "                <span class='caret'></span>"
                    + "            </button>"
                    + "            <ul class='dropdown-menu my-btn-waybill-process' role='menu'>"
                    + "                <li><a href='javascript:void(0)' data-my-process-id='1'"
                    + "                       data-my-waybill-id='" + waybill.waybillId + "'"
                    + "                       data-my-waybill-no='" + waybill.waybillNo + "'>已揽件</a></li>"
                    + "                <li><a href='javascript:void(0)' data-my-process-id='2'"
                    + "                       data-my-waybill-id='" + waybill.waybillId + "'"
                    + "                       data-my-waybill-no='" + waybill.waybillNo + "'>已收货</a></li>"
                    + "                <li><a href='javascript:void(0)' data-my-process-id='3'"
                    + "                       data-my-waybill-id='" + waybill.waybillId + "'"
                    + "                       data-my-waybill-no='" + waybill.waybillNo + "'>待处理</a></li>"
                    + "                <li><a href='javascript:void(0)' data-my-process-id='4'"
                    + "                       data-my-waybill-id='" + waybill.waybillId + "'"
                    + "                       data-my-waybill-no='" + waybill.waybillNo + "'>已中转</a></li>"
                    + "                <li><a href='javascript:void(0)' data-my-process-id='5'"
                    + "                       data-my-waybill-id='" + waybill.waybillId + "'"
                    + "                       data-my-waybill-no='" + waybill.waybillNo + "'>已签收</a></li>"
                    + "            </ul>"
                    + "        </div>"
                    + "        <button class='btn btn-primary my-show-waybill-detail' data-my-waybill-id='" + waybill.waybillId + "'>点击查看详情</button>"
                    + "    </td>"
                    + "</tr>";
            }
        );


        $('#table-pending-waybills tbody').html(html);


        //按钮监听
        $('#table-pending-waybills .my-btn-waybill-process a').click(function () {
            var waybillId = $(this).data("my-waybill-id");
            var waybillNo = $(this).data("my-waybill-no");
            var processId = $(this).data("my-process-id");
            console.log(processId);
            if (processId == 4) {
                $("#myPendingWaybillProcessModal").find(".modal-transfer-info").show();
            } else {
                $("#myPendingWaybillProcessModal").find(".modal-transfer-info").hide();
            }
            $('#myPendingWaybillProcessModal').find(".my-modal-title-waybill-no").html('-订单号:' + waybillNo);

            $('#myPendingWaybillProcessModal').modal();
            $('#myPendingWaybillProcessModal input[name="waybillId"]').val(waybillId);
            $('#myPendingWaybillProcessModal input[name="processId"]').val(processId);


        });

        $('#table-pending-waybills .my-show-waybill-detail').click(function () {
            var waybillId = $(this).data("my-waybill-id");
            window.location = jspContext +"/workbench/1/waybill/details?requestSrc=normal&waybillId=" + waybillId;
        });

    }




    //添加物流跟踪信息============================================================
    $('#myPendingWaybillProcessModal button[type="submit"]').click(function (e) {
        e.preventDefault();

        var data = $("#myPendingWaybillProcessModal form").serialize();
        console.log(data);
        $.ajax({
            url: jspContext+'/workbench/1/waybill/process',
            type: 'post',
            contentTypeString: 'application/x-www-form-urlencoded',
            dataType: 'json',
            data: data,
            success: function (data, textStatus, jqXHR) {
                console.log(data);
                //alert(data.message);
                //刷新待处理列表
                 refressAll();

                //TODO:消失对话框
                $('#myPendingWaybillProcessModal').modal("hide");
                $('#myPendingWaybillProcessModal').find(".my-modal-title-waybill-no").html('');
                $('#myPendingWaybillProcessModal form')[0].reset();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // 通常 textStatus 和 errorThrown 之中
                // 只有一个会包含信息
                alert("错误：" + textStatus);
                this; // 调用本次AJAX请求时传递的options参数
            }
        });


    })
    $('#myPendingWaybillProcessModal button[type="button"]').click(function (e) {


        $('#myPendingWaybillProcessModal').modal("hide");
        $('#myPendingWaybillProcessModal').find(".my-modal-title-waybill-no").html('');
        $('#myPendingWaybillProcessModal form')[0].reset();
    })


    //-----------------------------
    //查询的按钮
    $('#idPendingWaybillQueryButton').click(function () {
        var queryStr = $.trim($("#idPendingWaybillQueryInput").val());
        if (queryStr != "") {
            pendingWaybillsQueryParams["queryStr"] = queryStr;
        }else{
            delete pendingWaybillsQueryParams["queryStr"];
        }
        pendingWaybillsQueryParams["currentPage"] = 1;
        loadPendingWaybills(pendingWaybillsQueryParams);
    });

    $('#idBatchProcess').click(function () {
        alert('努力开发中....');
    });





    //==================================================================================
    //回收站
    //加载数据
    var recycleWaybillsQueryParams={pageSize:20,currentPage:1,"params":{isRecycle:1}};
    var loadRecycleWaybills = function(queryParams){
        if(queryParams == undefined){
            queryParams = {pageSize:20,currentPage:1,"params":{isRecycle:1}};
        }
        $.ajax({
            url: jspContext+'/workbench/1/waybills',
            type: 'post',
            contentType: 'application/json',
            dataType: 'json',
            data:JSON.stringify(queryParams),
            success: function (result, textStatus, jqXHR) {
                console.log(result);
                $('#idRecycleWaybillTotalCnt').html(result.totalSize)
                showRecycleWaybillTable(result.data);
                showPagination(result.pageSize,result.currentPage,result.totalSize,$("#idRecycleWaybillsPagination"),function(pageIndex){
                    recycleWaybillsQueryParams["currentPage"]=pageIndex;
                    loadRecycleWaybills(recycleWaybillsQueryParams);
                })
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // 通常 textStatus 和 errorThrown 之中
                // 只有一个会包含信息
                this; // 调用本次AJAX请求时传递的options参数
            }
        });
    }


    function showRecycleWaybillTable(waybills) {

        var html = "";
        if (waybills.length == 0) {
            html = "<tr><td colspan='8' align='center'>没有数据....</td></tr>";
            $('#table-recycle-waybills tbody').html(html);
            return;
        }

        $.each(waybills, function (index, waybill) {
                html += "<tr>"
                    + "    <td>"
                    + "        <div class='checkbox'>"
                    + "            <label>"
                    + "                <input class='list-checkbox' data-my-waybill-id='" + waybill.waybillId + "' type='checkbox'>"
                    + "            </label>"
                    + "        </div>"
                    + "    </td>"
                    + "    <td>" + waybill.sendDate + "</td>"
                    + "    <td>" + waybill.waybillNo + "</td>"
                    + "    <td>" + waybill.receiverName + "</td>"
                    + "    <td>" + waybill.startAddr + "</td>"
                    + "    <td>" + waybill.endAddr + "</td>"
                    + "    <td>" + getWaybillStatusText(waybill.waybillStatus) + "</td>"
                    + "    <td>"
                    + "        <div class='btn-group'>"
                    + "            <button type='button' class='btn btn-warning dropdown-toggle' data-toggle='dropdown'>"
                    + "                操作"
                    + "                <span class='caret'></span>"
                    + "            </button>"
                    + "            <ul class='dropdown-menu my-btn-waybill-process' role='menu'>"
                    + "                <li><a href='javascript:void(0)' data-my-process-id='1'"
                    + "                       data-my-waybill-id='" + waybill.waybillId + "'"
                    + "                       data-my-waybill-no='" + waybill.waybillNo + "'>还原</a></li>"
                    + "                <li><a href='javascript:void(0)' data-my-process-id='2'"
                    + "                       data-my-waybill-id='" + waybill.waybillId + "'"
                    + "                       data-my-waybill-no='" + waybill.waybillNo + "'>删除</a></li>"
                    + "            </ul>"
                    + "        </div>"
                    + "        <button class='btn btn-primary my-show-waybill-details' data-my-waybill-id='" + waybill.waybillId + "'>点击查看详情</button>"
                    + "    </td>"
                    + "</tr>";
            }
        )
        ;


        $('#table-recycle-waybills tbody').html(html);

        // 按钮监听=======
        $('#table-recycle-waybills .my-btn-waybill-process a').click(function () {
            var waybillId = $(this).data("my-waybill-id");
            var waybillNo = $(this).data("my-waybill-no");
            var processId = $(this).data("my-process-id");
            console.log(processId);
            var waybillIds = new Array();
            waybillIds.push(waybillId);
            params={"params":waybillIds};
            if(processId==1){
                recycleProcess(jspContext+'/workbench/waybill/restore',params);
            }else if(processId==2){
                recycleProcess(jspContext+'/workbench/waybill/delete',params);
            }

        });

        $('#table-recycle-waybills .my-show-waybill-details').click(function(){
            var waybillId = $(this).data('my-waybill-id');
            window.location=jspContext+"/workbench/1/waybill/details?requestSrc=normal&waybillId="+waybillId;
        });
    }

    //加载数据结束====================================================================================================


    //-----------------------------------------------------------------------------

    //批量删除
    $('#btnBatchDelete').click(function(){
        var waybillIds = new Array();
        $('#table-recycle-waybills input[type="checkbox"][class="list-checkbox"]:checked').each(function(index,item){
            var waybillId = $(this).data("my-waybill-id");
            console.log(waybillId)
            waybillIds.push(waybillId);

        })

        var params={"params":waybillIds}
        recycleProcess(jspContext+'/workbench/waybill/delete',params);

    });



    //批量恢复
    $('#btnBatchRestore').click(function(){
        var waybillIds = new Array();
        $('#table-recycle-waybills input[type="checkbox"][class="list-checkbox"]:checked').each(function(index,item){
            var waybillId = $(this).data("my-waybill-id");
            console.log(waybillId)
            waybillIds.push(waybillId);

        });

        var params={"params":waybillIds}
        recycleProcess(jspContext+'/workbench/waybill/restore',params);


    });

    var recycleProcess = function(url,json){
        $.ajax({
            url: url,
            type: 'post',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(json),
            success: function (data, textStatus, jqXHR) {
                console.log(data);
                refressAll();

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // 通常 textStatus 和 errorThrown 之中
                // 只有一个会包含信息
                console.log("错误：" + textStatus);
                this; // 调用本次AJAX请求时传递的options参数
            }
        });


    }





    //查询按钮
    $('#idRecycleQueryButton').click(function(){
        var queryStr = $.trim($('#idRecycleQueryInput').val());
        var queryParams = {params:{}};
        if(queryStr !== ""){
            recycleWaybillsQueryParams["queryStr"] = queryStr;
        }else{
            delete   recycleWaybillsQueryParams["queryStr"];
        }
        recycleWaybillsQueryParams["currentPage"]=1;
        loadRecycleWaybills(recycleWaybillsQueryParams);

    });



    //-------------------------------
    //获取状态文本
    var getWaybillStatusText = function (status) {
        switch (status) {
            case 0:
                return "新增";
            case 1:
                return "已揽件";
            case 2:
                return "已收货";
            case 3:
                return "待处理";
            case 4:
                return "已中转";
            case 5:
                return "已签收";
            default :
                return "未知";
        }
    }

    //日期选择器
    $("#processWaybillDatePicker").datetimepicker({
        format: 'yyyy-mm-dd hh:ii',
        language: 'zh-CN'

    });

    var refressAll = function(){
        loadWaybills(allWaybillsQueryParams);
        loadPendingWaybills(pendingWaybillsQueryParams);
        loadRecycleWaybills(recycleWaybillsQueryParams);
        //待处理订单数
        $.ajax({
            url: jspContext+'/workbench/1/waybills/total',
            type: 'post',
            contentType: 'application/json;charset=UTF-8',
            dataType: 'json',
            data: JSON.stringify({params: {waybillStatus: 3, isRecycle: 0}}),
            success: function (result, textStatus, jqXHR) {
                console.log(result);
                if (result.status == 0) {
                    $('#idPendingWaybillCnt').html(result.data);
                }

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // 通常 textStatus 和 errorThrown 之中
                // 只有一个会包含信息
                this; // 调用本次AJAX请求时传递的options参数
            }
        });
    }

    refressAll();
})